package com.baijiaoxi.common.model.base.service.extension;

import java.util.Date;

/**
 * 允许通过属性名称访问属性
 */
public interface FieldGetByNameService<T> {
    /**
     * 通过属性名获取对象属性值
     *
     * @param fieldName
     * @return
     */
    default Long getFieldValueAsLong(T entity, String fieldName) {
        return getFieldValueAsLong(entity, fieldName, null);
    }

    default Long getFieldValueAsLong(T entity, String fieldName, Long nullDefaultValue) {
        Object value = getFieldValue(entity, fieldName);
        return value == null ? nullDefaultValue : (Long) value;
    }

    default Integer getFieldValueAsInteger(T entity, String fieldName) {
        return getFieldValueAsInteger(entity, fieldName, null);
    }

    default Integer getFieldValueAsInteger(T entity, String fieldName, Integer nullDefaultValue) {
        Object value = getFieldValue(entity, fieldName);
        return value == null ? nullDefaultValue : (Integer) value;
    }

    default String getFieldValueAsString(T entity, String fieldName) {
        return getFieldValueAsString(entity, fieldName, null);
    }

    default String getFieldValueAsString(T entity, String fieldName, String nullDefaultValue) {
        Object value = getFieldValue(entity, fieldName);
        return value == null ? nullDefaultValue : (String) value;
    }


    default Date getFieldValueAsDate(T entity, String fieldName) {
        Object value = getFieldValue(entity, fieldName);
        return value == null ? null : (Date) value;
    }

    Object getFieldValue(T entity, String fieldName);
}
